package com.yygo.webapp.controller.loanrequest;

import com.yygo.Constants;
import com.yygo.model.LoanRequest;
import com.yygo.model.User;
import com.yygo.service.LoanRequestManager;
import com.yygo.service.UserManager;
import com.yygo.webapp.helper.ExtendedPaginatedList;
import com.yygo.webapp.helper.PaginateListFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ExtendedModelMap;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;
import java.util.List;

@Controller
@RequestMapping("/myloanrequests*")
public class MyLoanRequestController {
    private LoanRequestManager loanRequestManager;

    @Autowired
    public void setLoanRequestManager(@Qualifier("loanRequestManager") LoanRequestManager loanRequestManager) {
        this.loanRequestManager = loanRequestManager;
    }

    private UserManager userManager;
    @Autowired
    public void setUserManager(UserManager userManager) {
        this.userManager = userManager;
    }

    private PaginateListFactory paginateListFactory;
    @Autowired
    public void setPaginateListFactory(PaginateListFactory paginateListFactory) {
        this.paginateListFactory = paginateListFactory;
    }

    @RequestMapping(method = RequestMethod.GET)
    public Model handleRequest(@RequestParam(required = false, value = "phase") String phase, Principal principal, HttpServletRequest request)
    throws Exception {
        Model model = new ExtendedModelMap();

        if (phase == null) {
            return model;
        }
        ExtendedPaginatedList paginatedList = paginateListFactory
                .getPaginatedListFromRequest(request);

        User loginUser = userManager.getUserByUsername(principal.getName());

        List<LoanRequest> list = loanRequestManager.getMyLoanRequests(phase, loginUser, paginatedList);
        model.addAttribute("loanRequestList", paginatedList);

        return model;
    }
}
